﻿using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace Oliver.Apps.Windows7Countdown.Controls
{
    public partial class ImageCounter : UserControl
    {
        public ImageCounter()
        {
            InitializeComponent();

            _image.ImageFailed += new EventHandler<ExceptionRoutedEventArgs>(_image_ImageFailed);

            DispatcherTimer _timer = new DispatcherTimer();
            _timer.Interval = new TimeSpan(0, 0, 1);
            _timer.Tick += new EventHandler(_timer_Tick);
            _timer.Start();
        }

        void _image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            Debug.WriteLine(e.ErrorException.Message);
        }

        void _timer_Tick(object sender, EventArgs e)
        {
            ShowNextImage();
        }

        private void ShowNextImage()
        {
            //string baseUrl = App.Current.Host.Source.AbsoluteUri;
            //baseUrl = baseUrl.Substring(0, baseUrl.LastIndexOf("/"));
            //int day = _rnd.Next(_maxDay+1);
            //int version = _rnd.Next(_maxVersion);
            //string url = baseUrl + "/images/" + string.Format("{0:00}", day) + "_" + version + ".jpeg";
            //Uri uri = new Uri(url);
            //BitmapImage bi = new BitmapImage(uri);
            //bi.ImageFailed += bi_ImageFailed;
            //bi.ImageOpened += bi_ImageOpened;
            //_image_back.Source = bi;
        }

        void bi_ImageOpened(object sender, RoutedEventArgs e)
        {
            BitmapImage bi = sender as BitmapImage;
            bi.ImageFailed -= bi_ImageFailed;
            bi.ImageOpened -= bi_ImageOpened;
            _image.Source = _image_back.Source;
        }

        void bi_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            BitmapImage bi = sender as BitmapImage;
            bi.ImageFailed -= bi_ImageFailed;
            bi.ImageOpened -= bi_ImageOpened;
            Debug.WriteLine(e.ErrorException.Message);
        }

        private Random _rnd = new Random();

        private const int _maxDay = 49;
        private const int _maxVersion = 3;

        private int _currentDay;
        private int _currentVersion;
    }
}
